<?php

jimport('joomla.application.component.controller');

class bgController extends JController {
    public function display($cachable = false, $urlparams = false) {
        parent::display($cachable, $urlparams);
    }
    
    public function form(){
        $disp = JRequest::getVar('disp','center');
        $code = JRequest::getVar('ocba',''); 
        $model = $this->getModel();
        if($code !== ''){
            if(($disp == 'center' && substr($code,0,1) == '1') || ($disp == 'club' && substr($code,0,1) == '0')){
                JError::raiseError( 'Wrong parameter', 'CC CODE not found in database' );
            }
            $ocba = $model->getOcba($code);
            if(empty($ocba) ){
                JError::raiseError( 'Not found', 'CC CODE not found in database' );
            }
        }
        
        
        parent::display();
    }
    
    
    public function save(){
        $aut = new bgAuthorize();
        $model = $this->getModel();
        if(in_array('11', explode(',',$aut->getUserGroup()))){
            $ocba = $model->getUserOcba($aut->getUserID());
        }
        $disp= JRequest::getVar('disp');
        if($disp == 'center'){
           $data = array(
                'usce_data' =>  JRequest::getVar('usce_data'),
                'date'      =>  JRequest::getVar('year')."/".JRequest::getVar('month'),
                'ocba_code' =>  empty($ocba) ? JRequest::getVar('ocba_code') : $ocba,        
            );
            
            $model->saveUsce($data,JRequest::getVar('action')); 
            //$this->setRedirect('index.php?option=com_statistic&disp=center');
        } elseif($disp == 'club'){
            $data = array(
                'uscl_data' =>  JRequest::getVar('uscl_data'),
                'date'      =>  JRequest::getVar('year')."/".JRequest::getVar('month'),
                'ocba_code' =>  empty($ocba) ? JRequest::getVar('ocba_code') : $ocba,      
            );
            $model->saveUscl($data,JRequest::getVar('action')); 
            //$this->setRedirect('index.php?option=com_statistic&disp=club');
        }
        
        
        parent::display();
    }
    
    public function ajax_get_pref()
    {
        $model = $this->getModel();
        $prefs = $model->getPrefsByArea(JRequest::getVar('area_code'));
        echo "<option value='all'>全て</option>";
        foreach ($prefs as $pref) {
            echo "<option value='$pref->PREF_CODE'>$pref->PREF_NAME</option>";
        }
        $app = &JFactory::getApplication();
        $app->close();

    }
    
    public function ajax_search(){
        //get model
        $model = $this->getModel();
        
        //get data
        $data = JRequest::getVar('data');
        
        
        //get area and pref name to display
        $area = '全て';
        foreach($model->getArea() as $row){
            if($row->AREA_CODE == $data['area'])
                $area = $row->AREA_NAME;
        }
        $pref = '全て';
        foreach($model->getPrefs() as $row){
            if($row->PREF_CODE == $data['pref'])
                $pref = $row->PREF_NAME;
        }
        
            
        //get facolity name to display
        
        if($data['cc_type'] == 'center'){
            $tmp = HelperBG::getFacility();
            $facility = $tmp[$data['facility']];
            
            $filter = array(
                'period' => $data['period'],
                'period_f' => $data['period_f'],
                'year' => $data['year'],
                'month' => $data['month'],
                'facility' => $data['facility'],
                'area' => $data['area'],
                'pref' => $data['pref'],
                'ocba_code' => $data['ocba_code'],
                'ocba_name' => $data['ocba_name'],
            );
            $result = $model->loadUsce($filter);
            if(!empty($result['ocba_name'])){
                $ocba_name = "「".$result['ocba_name']."」";                  
            } elseif(!empty($data['ocba_name'])){
                $ocba_name = "「".urldecode($data['ocba_name'])."」";
            }
            
      
            echo
                "<table style='width: 100%; '>
                    <tr>
                        <td><label class='fl-left'>$ocba_name</label></td>
                        <td colspan='7'> 
                            <label class='fl-right'> 期間:$result[range]</label>
                        </td>
                    </tr>
                    <tr>
                        <td><label class='fl-left'>地区:$area</label></td>
                        <td class='left' ><label>都道府県:$pref</label></td>
                        <td colspan='5' class='left'><label>施設:$facility</label></td>
                        <td class='right'><label class='fl-right'>集計日:$result[last_update]</label></td>
                    </tr>
                </table>
                ";
            if(!empty($result['usce_data'])){
                echo"<table id='table_center' class='search_result_table'>
                    <tr>
                        <th>施設</th>
                        <th class='left'><b>ジャンル</th>";
                foreach($result['head'] as $head){
                    echo"<th><b>$head</b></th>";
                }
                echo "<th>合計</th>";
                echo "</tr>";
                $uscm_list = $model->getAllUscm();
                $rowspan = count($uscm_list)+1;
                $cell_width = 89/($data['period']+1);
                $first = true;
                foreach($uscm_list as $uscm_key => $uscm){
                    $color = $uscm->USCM_NUMF == 1 ? "background: #ADE2FF;" : "";
                    $sum_color = "background: #4AC0FF;";
                    echo "<tr>";
                        if($first){
                            echo "<th rowspan=$rowspan style='width: 3%;'><div class='rotate'>$facility</div></th>";                            
                        } else {
                            echo "<td style='display:none'>$facility</td>";
                        }  
                    $first = false;            
                    echo "<td style='width: 8%; $color'>$uscm->USCM_NAME</td>";
                    foreach($result['usce_data'][$uscm->USCM_CODE] as $row){
                        echo "<td class='center' style='width: $cell_width%; $color'>$row</td>";
                    }
                    $sum_row = empty($result['sum_row'][$uscm->USCM_CODE]) ? 0 : $result['sum_row'][$uscm->USCM_CODE];
                    echo "<td class='center' style='width: $cell_width%; $color'>$sum_row</td>";
                    echo "</tr>";
                }
                echo "<tr>";
                echo "<td style='display:none'>$facility</td>";
                echo "<td style='$sum_color'>人数小計</td>";
                foreach($result['sum_col'] as $sum){
                    echo "<td class='center' style='width: $cell_width%; $sum_color'>$sum</td>";
                }
                $total = array_sum($result['sum_col']) == 0 ? '-' : array_sum($result['sum_col']);
                echo "<td class='center' style='width: $cell_width%; $sum_color'>$total</td>";
                echo "</tr>";
                echo "</table>";
                echo "<div id='char_data' style='display:none'>".json_encode($result)."</div>";
            } else {
                echo "Nothing found";
            }
        } elseif($data['cc_type'] == 'club'){
            
            $filter = array(
                'period' => $data['period'],
                'period_f' => $data['period_f'],
                'year' => $data['year'],
                'month' => $data['month'],
                'area' => $data['area'],
                'pref' => $data['pref'],
                'ocba_code' => $data['ocba_code'],
                'ocba_name' => $data['ocba_name'],
            );
            $result = $model->loadUscl($filter);
            if(!empty($result['ocba_name'])){
                $ocba_name = "「".$result['ocba_name']."」";                  
            } elseif(!empty($data['ocba_name'])){
                $ocba_name = "「".urldecode($data['ocba_name'])."」";
            }

            echo
                "<table style='width: 100%; '>
                    <tr>
                        <td><label class='fl-left'>$ocba_name</label></td>
                        <td colspan='7'> 
                            <label class='fl-right'> 期間:$result[range]</label>
                        </td>
                    </tr>
                    <tr>
                        <td><label class='fl-left'>地区:$area</label></td>
                        <td class='left' ><label>都道府県:$pref</label></td>
                        <td colspan='5' class='left'><label></label></td>
                        <td class='right'><label class='fl-right'>集計日:$result[last_update]</label></td>
                    </tr>
                </table>
                ";
            if(!empty($result['uscl_data'])){
                echo"<table id='table_center'>
                    <tr>
                        <th style='visibility:hidden'></th>
                        <th class='left'><b>ジャンル</th>";
                foreach($result['head'] as $head){
                    echo"<th><b>$head</b></th>";
                }
                echo "<th>合計</th>";
                echo "</tr>";
                $pacm_list = $model->getAllPacm();
                $actm_list = $model->getAllActm();
                $rowspan = count($pacm_list);
                $cell_width = 89/($data['period']+1);

                $sum_color = "background: #4AC0FF;";
                foreach ($actm_list as $actm_key => $actm) {
                    echo "<tr><th rowspan=$rowspan style='width: 3%;'>$actm->ACTM_NAME</th>";
                    $first = true;
                    foreach($pacm_list as $pacm_key => $pacm){
                        $color = $pacm->PACM_NUMF == 1 ? "background: #ADE2FF;" : "";
                        if(!$first)
                            echo "<th style='display:none'>$actm->ACTM_NAME</th>";
                        echo "<td style='width: 8%; $color'>$pacm->PACM_NAME</td>";
                        foreach($result['uscl_data'][$actm->ACTM_CODE][$pacm->PACM_CODE] as $row){
                            echo "<td class='center' style='width: $cell_width%; $color'>$row</td>";
                        }
                        $sum_row = empty($result['sum_row'][$actm->ACTM_CODE][$pacm->PACM_CODE]) ? 0 : $result['sum_row'][$actm->ACTM_CODE][$pacm->PACM_CODE];
                        echo "<td class='center' style='width: $cell_width%; $color'>$sum_row</td>";
                        echo "</tr>";
                        
                        $first = false;
                    }
                }
                
                echo "<tr>";
                echo "<th colspan='2' style=''>合計人数</th>";
                echo "<th style='display:none'>合計人数</th>";
                foreach($result['sum_col'] as $sum){
                    echo "<td class='center' style='width: $cell_width%; $sum_color'>$sum</td>";
                }
                $total = array_sum($result['sum_col']) == 0 ? '-' : array_sum($result['sum_col']);
                echo "<td class='center' style='width: $cell_width%; $sum_color'>$total</td>";
                echo "</tr>";
                
                //
                echo "<tr>";
                echo "<th colspan='2'>合計活動日数</th>";
                echo "<th style='display:none'>合計活動日数</th>";
                foreach($result['sum_col2'] as $sum){
                    echo "<td class='center' style='width: $cell_width%;'>$sum</td>";
                }
                $total = array_sum($result['sum_col2']) == 0 ? '-' : array_sum($result['sum_col2']);
                echo "<td class='center' style='width: $cell_width%;'>$total</td>";
                echo "</tr>";
                
                echo "</table>";
            } else {
                echo "Nothing found";
            }
        }
        
        $app = &JFactory::getApplication();
        $app->close();
    }
    
    public function ajax_ranking() {
        //get model
        $model = $this->getModel();
        
        //get data
        $data = JRequest::getVar('data');
        
        
        //get area and pref name to display
        $area = '全て';
        foreach($model->getArea() as $row){
            if($row->AREA_CODE == $data['area'])
                $area = $row->AREA_NAME;
        }
        $pref = '全て';
        foreach($model->getPrefs() as $row){
            if($row->PREF_CODE == $data['pref'])
                $pref = $row->PREF_NAME;
        }
        
        //get ocba_name to display
        if(!empty($data['ocba_name']))
            $ocba_name = "「".$data['ocba_name']."」";
            
        $filter = array(
                'from' => $data['yfrom']."/".$data['mfrom'],
                'to' => $data['yto']."/".$data['mto'],
                'area' => $data['area'],
                'pref' => $data['pref'],
            );
            
        if($data['cc_type'] == 'center') {
            $tmp = HelperBG::getFacility();
            $facility = $tmp[$data['facility']];
            $filter['facility'] = $data['facility'];
            
            $result = $model->rank_center($filter);
            $text = "センター";
        } else {
            $result = $model->rank_club($filter);
            $text = "クラブ";
        }
        
        $show_facility = $data['cc_type'] == 'center' ? "施設:$facility" : "";
        echo 
        "<table style='width: 100%;'>".
            "<tr>".
                "<td colspan='9'>".
                    "<label class='fl-right'> 期間 : $data[yfrom]年 - $data[mfrom]月 ~ $data[yto]年 - $data[mto]月</label>".
                "</td>".
            "</tr>".
            "<tr>".
                "<td colspan='3'><label class='fl-left'>地区:$area</label></td>".
                "<td colspan='2' class='left' ><label>都道府県: $pref</label></td>".
                "<td colspan='3' class='left'><label class='facility'>$show_facility</label></td>".
                "<td class='right'><label class='fl-right'>集計日:$result[last_update]</label></td>".
            "</tr>".
        "</table>";
        
        echo 
   	    "<table class='adminlist' id='ranking_table'>".
            "<tbody>".
            "<tr>".
				"<th width='10%' class='center'>順位</th>".
				"<th width='15%' class='center'>".$text."コード</th>".
				"<th width='50%' class='center'>".$text."名</th>".
				"<th width='15%' class='left' style='text-align: right;'>活動人数（人）</th>"   .     
			"</tr>";
            $rank = 1;
            $last_val = 0;
        foreach($result['data'] as $key => $row) {
            $row_cls = $key % 2;
            if($last_val > $row->val){
                $rank ++;
            }
            $last_val = $row->val;
            //$rank = $key + 1;
            echo 
            "<tr class='row$row_cls'>".
    			"<td class='center'>" . $rank . "</td>".
                "<td class='center'>" . $row->OCBA_CODE . "</td>".
                "<td class='center'>" . $row->OCBA_NAME . "</td>".
                "<td class='left' style='text-align: right;'>" . $row->val . "</td>".
   		   "</tr>";
           
        }
        $app = &JFactory::getApplication();
        $app->close();
    }
    
    public function export(){
        $csv_output = JRequest::getVar('csv_data');
        $csv_output = mb_convert_encoding($csv_output,'Shift-JIS','UTF-8');
        $filename = "statistic_".date("Y-m-d_H-i",time());
    
        //$filename = "town_";

        header("Content-Encoding: Shift-JIS");
        header("Content-Type: text/csv; charset= Shift-JIS");
//        header("Content-Encoding: UTF-8");
//        header("Content-Type: text/csv; charset= UTF-8");
        header("Content-disposition: csv" . date("Y-m-d") . ".csv");
        header("Content-disposition:attachment; filename=" . $filename . ".csv");
        print_r($csv_output);
        
        $app = &JFactory::getApplication();
        $app->close();
    }
}